#include "StdAfx.h"
#include "GeneDirMd5.h"
#include "md5.h"
#include <fstream>

const TCHAR HEX[16] = {
	_T('0'), _T('1'), _T('2'), _T('3'),
	_T('4'), _T('5'), _T('6'), _T('7'),
	_T('8'), _T('9'), _T('A'), _T('B'),
	_T('C'), _T('D'), _T('E'), _T('F'),
};

CGeneDirMd5::CGeneDirMd5(void)
{
}

CGeneDirMd5::~CGeneDirMd5(void)
{
}

void CGeneDirMd5::GeneAllFileMd5(CString strDirPath, CString strRalPath)
{
	WIN32_FIND_DATA		stFindData;
	HANDLE				hFile;
	CString				strFileName;

	strFileName = strDirPath + _T("\\") + strRalPath + _T("\\*.*");
	hFile = ::FindFirstFile(strFileName, &stFindData);
	do 
	{
		if (!wcscmp(stFindData.cFileName, _T(".")) || !wcscmp(stFindData.cFileName, _T("..")))
		{
			continue;
		}
		else if (stFindData.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY)
		{
			GeneAllFileMd5(strDirPath, strRalPath + _T("\\") + stFindData.cFileName);
		}
		else
		{
			MD5			oMd5;
			FileInfo	stFileInfo;
			CString		strFullRalPath = strRalPath + _T("\\") + stFindData.cFileName;

			oMd5.update(ifstream(strDirPath + _T("\\") + strFullRalPath, std::ios::binary));
			stFileInfo.strFileName = stFindData.cFileName;
			stFileInfo.strRatPath = strFullRalPath;
			stFileInfo.strMd5 = Md5ToCString(oMd5.digest());

			m_vctFileInfo.push_back(stFileInfo);
		}
	} while (FindNextFile(hFile, &stFindData));
}

void CGeneDirMd5::ResetContent()
{
	m_vctFileInfo.clear();
}

CString CGeneDirMd5::Md5ToCString(const byte* pMd5)
{
	CString strTemp;

	for (int i = 0; i < 16; ++i)
	{
		strTemp += HEX[pMd5[i] / 16];
		strTemp += HEX[pMd5[i] % 16];
	}

	return strTemp;
}

void CGeneDirMd5::GetResult(VCT_FILE_INFO& vctFileInfo)
{
	vctFileInfo = m_vctFileInfo;
}
